package com.omega.exam.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.omega.exam.entity.Banner;
import com.omega.exam.entity.Category;
import com.omega.exam.entity.Question;
import com.omega.exam.mapper.BannerMapper;
import com.omega.exam.mapper.CategoryMapper;
import com.omega.exam.mapper.QuestionMapper;
import com.omega.exam.service.CategoryService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private QuestionMapper questionMapper;

    public List<Category> getCategories() {

        List<Category> list = categoryMapper.selectList(null);
        //一次性查出所有数量
        List<Map<String, Long>> questionCountlist = questionMapper.getCategoryQuestionCount();
        Map<Long, Long> map = questionCountlist.stream().collect(Collectors.toMap(m -> m.get("category_id"), m -> m.get("count")));
        for (Category category : list) {
            category.setCount(map.getOrDefault(category.getId(), 0L));
        }
        //        for (Category category : list) {
//            LambdaQueryWrapper<Question> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//            lambdaQueryWrapper.eq(Question::getCategoryId, category.getId());
//            Long count = questionMapper.selectCount(lambdaQueryWrapper);
//            category.setCount(count);
//        }


        return list;
    }

    public List<Category> gettree() {
        List<Category> list = categoryMapper.selectList(null);
        List<Map<String, Long>> questionlist = questionMapper.getCategoryQuestionCount();
        System.out.println(questionlist);
        Map<Long, Long> map = questionlist.stream().collect(Collectors.toMap(m -> m.get("category_id"), m -> m.get("count")));
        for (Category category : list) {
            category.setCount(map.getOrDefault(category.getId(), 0L));

        }
       return getchildren(list,0L);
    }
    private List<Category> getchildren(List<Category> children,Long pid){
        List<Category> list=new ArrayList<>();
        for (Category category:children){
            if(category.getParentId().equals(pid)){
                category.setChildren(getchildren(children,category.getId()));
                list.add(category);
            }
        }
        return list;

    }


} 